<template>
  <div class="reg">
    <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft" />
    <h1>注册</h1>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userName"
        name="pattern"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ pattern, required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="validator"
        label="密码"
        placeholder="请输入至少6位数字"
        :rules="[{ validator, required: true, message: '请填写正确密码' }]"
      />
      <van-field
        v-model="repwd"
        type="password"
        name="密码"
        label="再次输入密码"
        placeholder="密码"
        :rules="[{ required: true, message: '两次密码不一致' }]"
      />
      <div style="margin: 50px  16px 16px;">
        <van-button round block type="info" native-type="submit"
          >同意协议并注册</van-button
        >
      </div>
      <van-checkbox v-model="checked" shape="square">《注册协议》</van-checkbox>
    </van-form>

    <p>已有账号? <span @click="loginHandle">登录</span></p>
  </div>
</template>

<script>
import { regApi } from "../services/auth";
import { setToken } from "../utils/tools";
import { Toast } from "vant";
export default {
  data() {
    return {
      userName: "",
      password: "",
      repwd: "",
      checked: true,
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
    };
  },
  methods: {
    loginHandle() {
      this.$router.push({
        name: "Login",
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    validator(val) {
      return /^\d{6}$/.test(val);
    },
    async onSubmit() {
      if (this.checked == true) {
        if (this.password == this.repwd) {
          const res = await regApi({
            userName: this.userName,
            password: this.password,
          });
          if (res.code === 1) {
            setToken(res.data);
            Toast.success("注册成功");
            this.$router.push({
              name: "Home",
            });
          } else {
            Toast.fail(res.data);
          }
        } else {
          Toast.fail("两次密码不一致");
        }
      } else {
        Toast.fail("请勾选注册协议");
      }
    },
  },
};
</script>

<style scoped>
h1 {
  font-size: 1.5rem;
  margin-left: 1rem;
  margin-bottom: 2rem;
  margin-top: 2rem;
}
.van-field {
  margin-bottom: 1rem;
}
.van-checkbox {
  display: flex;
  margin-top: 1.8rem;
  justify-content: center;
  align-items: center;
}

p {
  position: fixed;
  bottom: 60px;
  left: 35%;
}
p span {
  color: rgba(123, 123, 214, 0.747);
}
</style>
